/**
 * 喝水提醒模块
 * 负责提醒用户按时喝水，记录喝水情况
 */
const { ipcRenderer } = require('electron');

class WaterTracker {
    constructor() {
        this.waterData = {
            dailyGoal: 2000, // 默认目标2000ml
            currentAmount: 0,
            records: [],
            // 新增历史记录数组，用于统计趋势
            historyRecords: [],
            settings: {
                gender: 'male',
                age: 25,
                weight: 60,
                activityLevel: 'sedentary',
                reminder: {
                    enabled: true,
                    interval: 60,
                    notification: true,
                    sound: true
                }
            }
        };

        // 定义饮品类型
        this.drinkTypes = [
            { id: 'water', name: '纯净水', icon: '🥛', factor: 1 },
            { id: 'tea', name: '茶', icon: '🍵', factor: 0.8 },
            { id: 'coffee', name: '咖啡', icon: '☕', factor: 0.5 },
            { id: 'juice', name: '果汁', icon: '🧃', factor: 0.7 },
            { id: 'milk', name: '牛奶', icon: '🥛', factor: 0.9 },
            { id: 'soup', name: '汤', icon: '🥣', factor: 0.7 }
        ];

        // 水波动画配置
        this.waveConfig = {
            amplitude: 20,
            frequency: 0.02,
            phase: 0
        };

        this.init();
        
        // 添加日期检查定时器
        this.startDateCheckTimer();
    }

    // 新增：启动日期检查定时器
    startDateCheckTimer() {
        // 每分钟检查一次日期变化
        setInterval(() => {
            this.checkDateChange();
        }, 60000); // 60秒检查一次
    }

    // 优化：检查日期变化和最近喝水记录
    checkDateChange() {
        const now = new Date();
        const today = now.toDateString();
        const lastDate = localStorage.getItem('lastWaterDate');
        
        // 检查最近的喝水记录时间
        let shouldReset = false;
        
        if (this.waterData.records.length > 0) {
            // 获取最近一条喝水记录的时间
            const latestRecord = this.waterData.records.reduce((latest, current) => {
                return latest.timestamp > current.timestamp ? latest : current;
            });
            
            // 将最近记录的时间转换为日期字符串进行比较
            const latestRecordDate = new Date(latestRecord.timestamp).toDateString();
            const isBeforeToday = new Date(latestRecordDate) < new Date(today);
            
            if (isBeforeToday) {
                shouldReset = true;
                this.showToast('检测到最近的喝水记录不是今天，已重置喝水数据', 'info');
            }
        }
        
        // 如果是新的一天或需要重置
        if (lastDate !== today || shouldReset) {
            // 保存昨天的记录到历史记录中
            if (lastDate && this.waterData.records.length > 0) {
                const yesterdayRecord = {
                    date: lastDate,
                    amount: this.waterData.currentAmount,
                    goal: this.waterData.dailyGoal,
                    records: [...this.waterData.records]
                };
                this.waterData.historyRecords.push(yesterdayRecord);
                
                // 只保留最近90天的历史记录
                if (this.waterData.historyRecords.length > 90) {
                    this.waterData.historyRecords.shift();
                }
            }
            
            // 重置今日数据
            this.waterData.currentAmount = 0;
            this.waterData.records = [];
            
            // 更新日期
            localStorage.setItem('lastWaterDate', today);
            
            // 保存并更新UI
            this.saveData();
            this.updateUI();
            
            // 显示新的一天的提醒
            if (!shouldReset) { // 只有在自然日期变更时显示这个提醒
                this.showToast('新的一天开始了，记得补充水分哦！', 'info');
            }
        }
    }

    init() {
        this.loadData();
        this.initElements();
        this.bindEvents();
        this.startReminders();
        this.updateUI();
        this.loadSettings();
        this.updateSettingsFormStyle();
    }

    // 优化：加载数据时的初始化检查
    loadData() {
        const savedData = localStorage.getItem('waterData');
        if (savedData) {
            const parsedData = JSON.parse(savedData);
            
            // 确保历史记录数组存在
            if (!parsedData.historyRecords) {
                parsedData.historyRecords = [];
            }
            
            this.waterData = parsedData;
            
            // 立即检查最近的喝水记录
            this.checkDateChange();
        }
        
        // 初始化时检查数据完整性
        this.validateAndRepairData();
    }

    // 新增：数据完整性检查和修复
    validateAndRepairData() {
        // 确保所有必要的数据结构都存在
        if (!this.waterData.historyRecords) {
            this.waterData.historyRecords = [];
        }
        
        // 修复可能的数据异常
        if (this.waterData.currentAmount < 0) {
            this.waterData.currentAmount = 0;
        }
        
        if (!Array.isArray(this.waterData.records)) {
            this.waterData.records = [];
        }
        
        // 清理无效的历史记录
        this.waterData.historyRecords = this.waterData.historyRecords.filter(record => 
            record && record.date && record.amount >= 0 && Array.isArray(record.records)
        );
        
        // 按日期排序历史记录
        this.waterData.historyRecords.sort((a, b) => 
            new Date(b.date) - new Date(a.date)
        );
        
        this.saveData();
    }

    saveData() {
        localStorage.setItem('waterData', JSON.stringify(this.waterData));
    }

    initElements() {
        // 进度相关元素
        this.progressCircle = document.querySelector('.water-progress-circle');
        this.waterWave = document.querySelector('.water-wave');
        this.currentAmount = document.querySelector('#water-current-div');
        this.targetAmount = document.querySelector('.water-target');

        // 快速添加按钮
        this.quickAddButtons = document.querySelectorAll('.water-amount-btn');
        this.customAddButton = document.querySelector('.btn-add-custom');

        // 记录列表
        this.recordsList = document.querySelector('.water-records-list');
        this.clearHistoryButton = document.querySelector('.btn-clear-history');

        // 趋势图表
        this.trendChart = document.querySelector('.water-trend-chart');
        this.trendButtons = document.querySelectorAll('.trend-btn');

        // 设置表单元素
        this.settingsForm = document.querySelector('.settings-form');
        this.saveSettingsButton = document.getElementById('save-water-settings');
    }

    bindEvents() {
        // 快速添加水量
        this.quickAddButtons.forEach(button => {
            button.addEventListener('click', () => {
                const amount = parseInt(button.dataset.amount);
                this.addWater(amount, this.drinkTypes[0]);
            });
        });

        // 自定义添加水量
        this.customAddButton.addEventListener('click', () => {
            this.showAddWaterDialog();
        });

        // 清空记录
        this.clearHistoryButton.addEventListener('click', () => {
            if (confirm('确定要清空今日的饮水记录吗？')) {
                this.waterData.currentAmount = 0;
                this.waterData.records = [];
                this.saveData();
                this.updateUI();
            }
        });

        // 趋势图切换
        this.trendButtons.forEach(button => {
            button.addEventListener('click', () => {
                this.trendButtons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
                this.updateTrendChart(button.dataset.period);
            });
        });

        // 保存设置
        this.saveSettingsButton.addEventListener('click', () => {
            this.saveSettings();
        });
    }

    showAddWaterDialog() {
        // 创建对话框HTML
        const dialog = document.createElement('div');
        dialog.className = 'water-dialog';
        dialog.innerHTML = `
            <div class="water-dialog-content">
                <h3>添加饮水记录</h3>
                <div class="drink-type-selector">
                    ${this.drinkTypes.map(type => `
                        <div class="drink-type-item" data-type="${type.id}">
                            <span class="drink-icon">${type.icon}</span>
                            <span class="drink-name">${type.name}</span>
                        </div>
                    `).join('')}
                </div>
                <div class="amount-input">
                    <input type="number" id="water-amount" placeholder="输入饮水量" min="0" max="2000" value="200">
                    <span class="unit">ml</span>
                </div>
                <div class="time-selector">
                    <input type="time" id="water-time" value="${new Date().toTimeString().slice(0, 5)}">
                </div>
                <div class="dialog-buttons">
                    <button class="btn-cancel">取消</button>
                    <button class="btn-confirm">确定</button>
                </div>
            </div>
        `;

        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .water-dialog {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
                opacity: 0;
                transition: opacity 0.3s ease;
            }
            .water-dialog.show {
                opacity: 1;
            }
            .water-dialog-content {
                background: white;
                padding: 20px;
                border-radius: 12px;
                min-width: 300px;
                max-width: 90%;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                transform: translateY(20px);
                transition: transform 0.3s ease;
            }
            .water-dialog.show .water-dialog-content {
                transform: translateY(0);
            }
            .drink-type-selector {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 10px;
                margin: 15px 0;
            }
            .drink-type-item {
                padding: 10px;
                text-align: center;
                border: 1px solid #eee;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.3s;
                background: #fff;
            }
            .drink-type-item.selected {
                background: #e3f2fd;
                border-color: #2196f3;
                transform: translateY(-2px);
                box-shadow: 0 2px 8px rgba(33, 150, 243, 0.2);
            }
            .drink-icon {
                font-size: 28px;
                display: block;
                margin-bottom: 8px;
                transition: transform 0.3s ease;
            }
            .drink-type-item:hover .drink-icon {
                transform: scale(1.1);
            }
            .drink-name {
                font-size: 14px;
                color: #333;
            }
            .amount-input {
                margin: 15px 0;
                position: relative;
            }
            .amount-input input {
                width: 275px;
                padding: 12px 40px 12px 15px;
                border: 1px solid #ddd;
                border-radius: 8px;
                font-size: 16px;
                transition: all 0.3s;
            }
            .amount-input input:focus {
                border-color: #2196f3;
                box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1);
                outline: none;
            }
            .unit {
                position: absolute;
                right: 15px;
                top: 50%;
                transform: translateY(-50%);
                color: #666;
                font-size: 14px;
            }
            .time-selector {
                margin: 15px 0;
            }
            .time-selector input {
                width: 300px;
                padding: 12px 15px;
                border: 1px solid #ddd;
                border-radius: 8px;
                font-size: 16px;
                transition: all 0.3s;
            }
            .time-selector input:focus {
                border-color: #2196f3;
                box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1);
                outline: none;
            }
            .dialog-buttons {
                display: flex;
                justify-content: flex-end;
                gap: 10px;
                margin-top: 20px;
            }
            .dialog-buttons button {
                padding: 10px 24px;
                border-radius: 8px;
                border: none;
                cursor: pointer;
                transition: all 0.3s;
                font-size: 15px;
                font-weight: 500;
            }
            .btn-cancel {
                background: #f5f5f5;
                color: #666;
            }
            .btn-confirm {
                background: #2196f3;
                color: white;
            }
            .btn-cancel:hover {
                background: #e0e0e0;
            }
            .btn-confirm:hover {
                background: #1976d2;
            }
            @media (max-width: 480px) {
                .drink-type-selector {
                    grid-template-columns: repeat(2, 1fr);
                }
                .water-dialog-content {
                    padding: 15px;
                }
                .dialog-buttons button {
                    padding: 8px 16px;
                }
            }
        `;
        document.head.appendChild(style);

        // 添加到页面
        document.body.appendChild(dialog);

        // 关闭对话框函数
        const closeDialog = () => {
            dialog.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(dialog);
            }, 300);
        };

        // 添加显示动画
        requestAnimationFrame(() => {
            dialog.classList.add('show');
        });

        // 事件处理
        let selectedType = 'water';
        const typeItems = dialog.querySelectorAll('.drink-type-item');
        typeItems.forEach(item => {
            item.addEventListener('click', () => {
                typeItems.forEach(i => i.classList.remove('selected'));
                item.classList.add('selected');
                selectedType = item.dataset.type;
                const type = this.drinkTypes.find(t => t.id === selectedType);
                // const amount = parseInt(dialog.querySelector('#water-amount').value);
                dialog.querySelector('#water-amount').value = 200 * type.factor;
            });
        });

        // 默认选中第一个类型
        typeItems[0].classList.add('selected');

        // 点击对话框外部关闭
        dialog.addEventListener('click', (e) => {
            if (e.target === dialog) {
                closeDialog();
            }
        });

        // 确认和取消按钮
        dialog.querySelector('.btn-cancel').addEventListener('click', closeDialog);

        dialog.querySelector('.btn-confirm').addEventListener('click', () => {
            const amount = parseInt(dialog.querySelector('#water-amount').value);
            const time = dialog.querySelector('#water-time').value;
            if (amount && amount > 0) {
                const type = this.drinkTypes.find(t => t.id === selectedType);
                const adjustedAmount = Math.round(amount);
                this.addWater(adjustedAmount, type, time);
                closeDialog();
            } else {
                this.showToast('请输入有效的饮水量');
            }
        });
    }

    addWater(amount, drinkType, time = null) {
        const recordTime = time ? new Date(`${new Date().toDateString()} ${time}`) : new Date();
        this.waterData.currentAmount += amount;
        this.waterData.records.push({
            amount,
            drinkType: drinkType.id,
            drinkName: drinkType.name,
            drinkIcon: drinkType.icon,
            time: recordTime.toLocaleTimeString(),
            timestamp: recordTime.getTime()
        });
        this.saveData();
        this.updateUI();

        // 根据完成度显示不同类型的提醒
        const percentage = (this.waterData.currentAmount / this.waterData.dailyGoal) * 100;
        let toastType = 'success';
        let message = `成功添加 ${amount}ml ${drinkType.name}`;

        if (percentage >= 100) {
            message += '\n🎉 恭喜达成今日目标！';
        } else if (percentage >= 80) {
            message += '\n💪 即将达成目标，继续加油！';
            toastType = 'info';
        }

        this.showToast(message, toastType);
    }

    calculateDailyGoal() {
        const { gender, weight, age, activityLevel } = this.waterData.settings;
        let baseAmount = weight * 35; // 基础计算：每公斤35ml

        // 性别调整
        if (gender === 'male') {
            baseAmount *= 1.1; // 男性多10%
        }

        // 年龄调整
        if (age < 18) {
            baseAmount *= 1.1; // 青少年多10%
        } else if (age > 65) {
            baseAmount *= 0.9; // 老年人少10%
        }

        // 活动量调整
        switch (activityLevel) {
            case 'moderate':
                baseAmount += 500; // 中等运动加500ml
                break;
            case 'active':
                baseAmount += 1000; // 高强度运动加1000ml
                break;
        }

        // 天气调整（这里可以接入实际天气API）
        const isHotWeather = true; // 模拟炎热天气
        if (isHotWeather) {
            baseAmount += 500;
        }

        return Math.round(baseAmount);
    }

    updateUI() {
        // 更新进度圈
        const percentage = (this.waterData.currentAmount / this.waterData.dailyGoal) * 100;
        const clampedPercentage = Math.min(100, Math.max(0, percentage));

        // 创建水波动画
        this.updateWaveAnimation(clampedPercentage);

        try {
            // 检查waterData是否存在
            if (!this.waterData) {
                throw new Error('waterData未初始化');
            }

            // 检查currentAmount和dailyGoal是否存在
            if (typeof this.waterData.currentAmount === 'undefined' || typeof this.waterData.dailyGoal === 'undefined') {
                throw new Error('currentAmount或dailyGoal未定义');
            }

            // 检查DOM元素是否存在
            if (!this.currentAmount || !this.targetAmount) {
                throw new Error('currentAmount或targetAmount DOM元素未找到');
            }

            this.currentAmount.textContent = this.waterData.currentAmount;
            this.targetAmount.textContent = `/ ${this.waterData.dailyGoal} 毫升`;
        } catch (error) {
            console.error('更新UI时发生错误:', error.message);
            // 可以添加默认值显示
            if (this.currentAmount) this.currentAmount.textContent = '0';
            if (this.targetAmount) this.targetAmount.textContent = '/ 0 毫升';
        }

        // 更新记录列表
        this.updateRecordsList();

        // 更新趋势图表
        this.updateTrendChart('week');

        // 更新健康评分
        this.updateHealthScore();
    }

    updateWaveAnimation(percentage) {
        // 确保水波容器存在
        if (!this.waterWave) return;

        // 更新水波高度（从底部往上升）
        const height = `${percentage}%`;
        this.waterWave.style.height = height;
        this.waterWave.style.top = 'auto'; // 移除top属性，改用bottom定位
        this.waterWave.style.bottom = '0';

        // 添加水波动画样式
        const style = document.createElement('style');
        style.textContent = `
            .water-wave {
                position: absolute;
                left: 0;
                right: 0;
                bottom: 0;
                background: linear-gradient(180deg, 
                    rgba(33, 150, 243, 0.8) 0%,
                    rgba(33, 150, 243, 0.4) 100%);
                transition: height 0.5s cubic-bezier(0.4, 0, 0.2, 1);
                border-radius: 0 0 50% 50% / 0 0 8px 8px;
                transform-origin: 50% 100%;
                overflow: hidden;
            }

            .water-wave::before,
            .water-wave::after {
                content: '';
                position: absolute;
                left: 0;
                right: 0;
                height: 100%;
                background-repeat: repeat-x;
                opacity: 0.5;
            }

            .water-wave::before {
                top: 5px;
                height: 10px;
                background-image: 
                    radial-gradient(circle at 50% 0%, 
                        rgba(255,255,255,0.3) 25%, 
                        transparent 50%);
                background-size: 20px 10px;
                animation: waveTop 3s linear infinite;
            }

            .water-wave::after {
                bottom: 5px;
                height: 10px;
                background-image: 
                    radial-gradient(circle at 50% 100%, 
                        rgba(255,255,255,0.3) 25%, 
                        transparent 50%);
                background-size: 30px 10px;
                animation: waveBottom 4s linear infinite;
            }

            @keyframes waveTop {
                0% { background-position: 0 0; }
                100% { background-position: 20px 0; }
            }

            @keyframes waveBottom {
                0% { background-position: 0 0; }
                100% { background-position: 30px 0; }
            }

            .water-progress-circle {
                position: relative;
                width: 200px;
                height: 200px;
                border-radius: 50%;
                background: var(--bg-300);
                box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.1);
                overflow: hidden;
                transition: transform 0.3s ease;
            }

            .water-progress-circle:hover {
                transform: scale(1.02);
            }

            .water-progress-text {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: 1;
                text-align: center;
                color: var(--text-primary);
                transition: color 0.3s ease;
                width: 100%;
            }

            .water-current {
                font-size: 36px;
                font-weight: bold;
                line-height: 1.2;
                margin-bottom: 5px;
                background: linear-gradient(180deg, var(--text-primary) 0%, var(--text-secondary) 100%);
                -webkit-background-clip: text;
            }

            .water-target {
                font-size: 14px;
                opacity: 0.7;
            }

            .water-percentage {
                font-size: 16px;
                color: var(--text-secondary);
                margin-top: 5px;
            }

            .water-wave.warning {
                background: linear-gradient(180deg, 
                    rgba(255, 152, 0, 0.8) 0%,
                    rgba(255, 152, 0, 0.4) 100%);
            }

            .water-wave.danger {
                background: linear-gradient(180deg, 
                    rgba(244, 67, 54, 0.8) 0%,
                    rgba(244, 67, 54, 0.4) 100%);
            }

            .water-wave.success {
                background: linear-gradient(180deg, 
                    rgba(76, 175, 80, 0.8) 0%,
                    rgba(76, 175, 80, 0.4) 100%);
            }

            @media (max-width: 480px) {
                .water-progress-circle {
                    width: 150px;
                    height: 150px;
                }

                .water-current {
                    font-size: 28px;
                }

                .water-target {
                    font-size: 12px;
                }

                .water-percentage {
                    font-size: 14px;
                }
            }
        `;

        // 移除旧的样式
        const oldStyle = document.querySelector('style[data-wave-animation]');
        if (oldStyle) {
            oldStyle.remove();
        }

        // 添加新的样式
        style.setAttribute('data-wave-animation', 'true');
        document.head.appendChild(style);

        // 根据百分比调整颜色和类名
        const waveClasses = ['water-wave'];
        if (percentage < 30) {
            waveClasses.push('danger');
        } else if (percentage < 60) {
            waveClasses.push('warning');
        } else if (percentage >= 100) {
            waveClasses.push('success');
        }

        this.waterWave.className = waveClasses.join(' ');

        // 更新进度文本
        const progressText = document.querySelector('.water-progress-text');
        if (progressText) {
            progressText.innerHTML = `
                <div class="water-current">${this.waterData.currentAmount}ml</div>
                <div class="water-target">${this.waterData.dailyGoal}ml</div>
                <div class="water-percentage">${Math.round(percentage)}%</div>
            `;

            if (percentage < 30) {
                progressText.style.color = '#f44336';
            } else if (percentage < 60) {
                progressText.style.color = '#ff9800';
            } else if (percentage >= 100) {
                progressText.style.color = '#4caf50';
            } else {
                progressText.style.color = 'rgb(55, 136, 216)';
            }
        }
    }

    updateRecordsList() {
        const records = this.waterData.records.sort((a, b) => b.timestamp - a.timestamp);
        const timeFormatter = new Intl.DateTimeFormat('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        });

        // 添加记录列表样式
        const style = document.createElement('style');
        style.textContent = `
            .water-records-list {
                max-height: 400px;
                overflow-y: auto;
                padding: 10px;
                border-radius: 12px;
                background: var(--bg-300);
            }

            .record-item {
                display: flex;
                align-items: center;
                padding: 15px;
                margin-bottom: 10px;
                background: var(--bg-200);
                border-radius: 10px;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
                transition: all 0.3s ease;
            }

            .record-item:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            .record-icon {
                font-size: 24px;
                margin-right: 15px;
                width: 40px;
                height: 40px;
                display: flex;
                align-items: center;
                justify-content: center;
                background: #f0f7ff;
                border-radius: 50%;
            }

            .record-info {
                flex: 1;
            }

            .record-time {
                color: #333;
                font-size: 14px;
                margin-bottom: 4px;
            }

            .time-diff {
                color: #666;
                font-size: 12px;
                margin-left: 8px;
            }

            .record-amount {
                color: #2196f3;
                font-weight: 500;
            }

            .btn-delete-record {
                opacity: 0;
                background: none;
                border: none;
                color: #f44336;
                cursor: pointer;
                padding: 8px;
                border-radius: 50%;
                transition: all 0.3s ease;
            }

            .record-item:hover .btn-delete-record {
                opacity: 1;
            }

            .btn-delete-record:hover {
                background: #fee8e7;
            }

            .empty-state {
                text-align: center;
                padding: 40px 20px;
                color: #666;
            }

            .empty-state i {
                font-size: 48px;
                color: #ccc;
                margin-bottom: 15px;
            }

            .empty-state p {
                margin: 0;
                font-size: 14px;
            }

            /* 自定义滚动条样式 */
            .water-records-list::-webkit-scrollbar {
                width: 6px;
            }

            .water-records-list::-webkit-scrollbar-track {
                background: #f5f5f5;
                border-radius: 3px;
            }

            .water-records-list::-webkit-scrollbar-thumb {
                background: #ddd;
                border-radius: 3px;
            }

            .water-records-list::-webkit-scrollbar-thumb:hover {
                background: #ccc;
            }
        `;

        // 移除旧的样式
        const oldStyle = document.querySelector('style[data-records-list]');
        if (oldStyle) {
            oldStyle.remove();
        }

        // 添加新的样式
        style.setAttribute('data-records-list', 'true');
        document.head.appendChild(style);

        this.recordsList.innerHTML = records.map(record => {
            const recordTime = new Date(record.timestamp);
            const timeStr = timeFormatter.format(recordTime);
            const timeDiff = this.getTimeDiff(recordTime);
            const drinkType = this.drinkTypes.find(t => t.id === record.drinkType) || this.drinkTypes[0];

            return `
                <div class="record-item">
                    <div class="record-icon">${drinkType.icon}</div>
                    <div class="record-info">
                        <div class="record-time">
                            ${timeStr}
                            <span class="time-diff">${timeDiff}</span>
                        </div>
                        <div class="record-amount">
                            ${drinkType.name} +${record.amount}ml
                        </div>
                    </div>
                    <button class="btn-delete-record" data-timestamp="${record.timestamp}" title="删除记录">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
        }).join('');

        // 添加删除按钮事件监听
        this.recordsList.querySelectorAll('.btn-delete-record').forEach(button => {
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                if (confirm('确定要删除这条记录吗？')) {
                    const timestamp = parseInt(e.currentTarget.dataset.timestamp);
                    this.deleteRecord(timestamp);
                }
            });
        });

        // 如果没有记录，显示空状态
        if (records.length === 0) {
            this.recordsList.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-glass-water"></i>
                    <p>今天还没有喝水记录哦</p>
                    <p style="color: #999; margin-top: 8px; font-size: 12px;">点击上方按钮添加饮水记录</p>
                </div>
            `;
        }
    }

    getTimeDiff(timestamp) {
        const now = new Date();
        const diff = now - timestamp;
        const minutes = Math.floor(diff / 60000);

        if (minutes < 1) return '刚刚';
        if (minutes < 60) return `${minutes}分钟前`;

        const hours = Math.floor(minutes / 60);
        if (hours < 24) return `${hours}小时前`;

        return '今天';
    }

    updateTrendChart(period) {
        const container = this.trendChart;
        const now = new Date();
        let data = [];
        let labels = [];
        
        // 根据不同时间段处理数据
        switch(period) {
            case 'week':
                // 获取最近7天的数据
                for (let i = 6; i >= 0; i--) {
                    const date = new Date(now);
                    date.setDate(date.getDate() - i);
                    const dateStr = date.toDateString();
                    // 查找对应日期的记录
                    const record = this.waterData.historyRecords.find((r,index) => r.date === dateStr);
                    const amount = record ? record.amount : 0;
                    const goal = record ? record.goal : this.waterData.dailyGoal;
                    
                    // 如果是今天，使用当前数据
                    if (i === 0) {
                        const percentage = Math.round((this.waterData.currentAmount / this.waterData.dailyGoal) * 100);
                        data.push({
                            amount: this.waterData.currentAmount,
                            goal: this.waterData.dailyGoal,
                            percentage: percentage > 100 ? 100 : percentage
                        });
                    } else {
                        const percentage = Math.round((amount / goal) * 100);
                        data.push({
                            amount: amount,
                            goal: goal,
                            percentage: percentage > 100 ? 100 : percentage
                        });
                    }
                    
                    // 格式化日期标签
                    labels.push(this.formatDate(date, 'week'));
                }
                break;
                
            case 'month':
                // 获取最近30天的数据
                for (let i = 29; i >= 0; i--) {
                    const date = new Date(now);
                    date.setDate(date.getDate() - i);
                    const dateStr = date.toDateString();
                    
                    const record = this.waterData.historyRecords.find(r => r.date === dateStr);
                    const amount = record ? record.amount : 0;
                    const goal = record ? record.goal : this.waterData.dailyGoal;
                    
                    if (i === 0) {
                        data.push({
                            amount: this.waterData.currentAmount,
                            goal: goal,
                            percentage: Math.round((this.waterData.currentAmount / goal) * 100)
                        });
                    } else {
                        data.push({
                            amount: amount,
                            goal: goal,
                            percentage: Math.round((amount / goal) * 100)
                        });
                    }
                    
                    labels.push(this.formatDate(date, 'month'));
                }
                break;
        }
        
        // 渲染趋势图表
        this.renderTrendChart(container, data, labels, period);
    }
    
    // 新增：日期格式化方法
    formatDate(date, type) {
        const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
        
        if (type === 'week') {
            return `${date.getMonth() + 1}/${date.getDate()}\n周${weekDays[date.getDay()]}`;
        } else {
            return `${date.getMonth() + 1}/${date.getDate()}`;
        }
    }
    
    // 优化：渲染趋势图表
    renderTrendChart(container, data, labels, period) {
        // 清空容器
        container.innerHTML = '';
        
        // 创建图表样式
        const style = document.createElement('style');
        style.textContent = `
            .trend-chart {
                padding: 20px;
                background: var(--bg-300);
                border-radius: 12px;
                overflow: hidden;
            }
            .chart-container {
                position: relative;
                height: 250px;
                margin-top: 20px;
                padding: 20px 10px 30px;
            }
            .chart-bar {
                position: absolute;
                bottom: 30px;
                width: ${period === 'week' ? '12%' : '2.8%'};
                background: linear-gradient(to top, rgba(33, 150, 243, 0.7), rgba(33, 150, 243, 0.3));
                border-radius: 6px 6px 0 0;
                transition: all 0.3s ease;
                cursor: pointer;
            }
            .chart-bar:hover {
                transform: scaleY(1.02);
                background: linear-gradient(to top, rgba(33, 150, 243, 0.9), rgba(33, 150, 243, 0.5));
            }
            .chart-bar.low {
                background: linear-gradient(to top, rgba(255, 152, 0, 0.7), rgba(255, 152, 0, 0.3));
            }
            .chart-bar.low:hover {
                background: linear-gradient(to top, rgba(255, 152, 0, 0.9), rgba(255, 152, 0, 0.5));
            }
            .chart-bar.high {
                background: linear-gradient(to top, rgba(76, 175, 80, 0.7), rgba(76, 175, 80, 0.3));
            }
            .chart-bar.high:hover {
                background: linear-gradient(to top, rgba(76, 175, 80, 0.9), rgba(76, 175, 80, 0.5));
            }
            .chart-label {
                position: absolute;
                bottom: 0;
                width: ${period === 'week' ? '12%' : '2.8%'};
                text-align: center;
                font-size: 12px;
                color: var(--text-secondary);
                white-space: pre-line;
                transform: translateY(100%);
                transition: transform 0.3s ease;
            }
            .chart-bar:hover + .chart-label {
                transform: translateY(90%);
                font-weight: bold;
            }
            .chart-goal-line {
                position: absolute;
                width: 100%;
                border-top: 2px dashed rgba(158, 158, 158, 0.5);
                transition: all 0.3s ease;
            }
            .chart-goal-line::after {
                content: '目标量';
                position: absolute;
                right: -40px;
                top: -10px;
                font-size: 12px;
                color: var(--text-secondary);
            }
            .chart-percentage {
                position: absolute;
                top: -25px;
                width: 100%;
                text-align: center;
                font-size: 12px;
                color: var(--text-secondary);
                opacity: 0;
                transform: translateY(5px);
                transition: all 0.3s ease;
            }
            .chart-bar:hover .chart-percentage {
                opacity: 1;
                transform: translateY(0);
            }
            .chart-grid {
                position: absolute;
                width: 100%;
                height: calc(100%);
                bottom: 30px;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                pointer-events: none;
            }
            .grid-line {
                width: 100%;
                border-top: 1px dashed rgba(158, 158, 158, 0.2);
            }
            .grid-label {
                position: absolute;
                left: -35px;
                font-size: 10px;
                color: var(--text-secondary);
                transform: translateY(-50%);
            }
        `;
        document.head.appendChild(style);
        
        // 创建图表容器
        const chartContainer = document.createElement('div');
        chartContainer.className = 'chart-container';
        
        // 添加网格线
        const gridContainer = document.createElement('div');
        gridContainer.className = 'chart-grid';
        for (let i = 0; i <= 5; i++) {
            const line = document.createElement('div');
            line.className = 'grid-line';
            const label = document.createElement('div');
            label.className = 'grid-label';
            label.textContent = Math.round(100 - i * 20) + '%';
            line.appendChild(label);
            gridContainer.appendChild(line);
        }
        chartContainer.appendChild(gridContainer);
        
        // 添加目标线
        const goalLine = document.createElement('div');
        goalLine.className = 'chart-goal-line';
        goalLine.style.bottom = '310px';  // 80% 的高度位置
        chartContainer.appendChild(goalLine);
        
        // 添加柱状图和标签
        data.forEach((item, index) => {
            const bar = document.createElement('div');
            bar.className = 'chart-bar ' + (item.percentage < 60 ? 'low' : item.percentage > 100 ? 'high' : '');
            bar.style.left = (index * (100 / (data.length - 1))) + '%';
            bar.style.height = Math.min(item.percentage, 150) + '%';
            
            const percentage = document.createElement('div');
            percentage.className = 'chart-percentage';
            percentage.textContent = item.amount + 'ml (' + item.percentage + '%)';
            bar.appendChild(percentage);
            
            const label = document.createElement('div');
            label.className = 'chart-label';
            label.style.left = (index * (100 / (data.length - 1))) + '%';
            label.textContent = labels[index];
            
            // 添加悬停提示
            bar.title = '饮水量: ' + item.amount + 'ml\n目标: ' + item.goal + 'ml\n完成度: ' + item.percentage + '%';
            
            chartContainer.appendChild(bar);
            chartContainer.appendChild(label);
        });
        
        container.appendChild(chartContainer);
    }

    updateHealthScore() {
        // 获取昨天的日期字符串
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        const yesterdayStr = yesterday.toDateString();
        
        // 从历史记录中查找昨天的数据
        const yesterdayRecord = this.waterData.historyRecords.find(r => r.date === yesterdayStr);
        const yesterdayAmount = yesterdayRecord ? yesterdayRecord.amount : 0;
        const yesterdayGoal = yesterdayRecord ? yesterdayRecord.goal : this.waterData.dailyGoal;
        const percentage = (yesterdayAmount / yesterdayGoal) * 100;
        // 计算今天的进度百分比
        const todayPercentage = Math.round((this.waterData.currentAmount / this.waterData.dailyGoal) * 100);
        const todayScore = Math.min(todayPercentage, 100); // 限制最大值为100%
        document.querySelector('#today-progress').textContent = `${todayScore}%`;
        document.querySelector('#health-score').textContent = `${todayScore}`;
        // 更新进度指标
        document.querySelector('#yesterday-progress').textContent = `${Math.round(percentage > 100 ? 100 : percentage)}%`;
    }

    saveSettings() {
        // 获取所有输入值
        const gender = document.getElementById('gender').value;
        const age = document.getElementById('age').value;
        const weight = document.getElementById('weight').value;
        const activityLevel = document.getElementById('activity-level').value;
        const reminderInterval = document.getElementById('reminder-interval').value;

        // 验证输入
        let errors = [];
        if (!gender) errors.push('请选择性别');
        if (!age || age < 1 || age > 120) errors.push('请输入有效年龄（1-120岁）');
        if (!weight || weight < 20 || weight > 300) errors.push('请输入有效体重（20-300kg）');
        if (!activityLevel) errors.push('请选择活动量');
        if (!reminderInterval || reminderInterval < 15 || reminderInterval > 240) errors.push('请输入有效提醒间隔（15-240分钟）');

        // 如果有错误，显示错误信息并返回
        if (errors.length > 0) {
            this.showToast(errors.join('\n'), 'error');
            return;
        }

        const settings = {
            gender: gender,
            age: parseInt(age),
            weight: parseInt(weight),
            activityLevel: activityLevel,
            reminder: {
                enabled: document.getElementById('reminder-enabled').checked,
                interval: parseInt(reminderInterval),
                notification: document.getElementById('notification-enabled').checked,
                sound: document.getElementById('sound-enabled').checked
            }
        };

        this.waterData.settings = settings;
        this.waterData.dailyGoal = this.calculateDailyGoal();
        this.saveData();
        this.updateUI();
        this.showToast('设置已保存', 'success');
        this.startReminders();
    }

    // 添加新方法：更新设置表单样式
    updateSettingsFormStyle() {
        const style = document.createElement('style');
        style.textContent = `
            .settings-form {
                padding: 20px;
                background: var(--bg-300);
                border-radius: 12px;
                margin-top: 20px;
            }

            .settings-form .form-group {
                margin-bottom: 20px;
            }

            .settings-form label {
                display: block;
                margin-bottom: 8px;
                color: var(--text-primary);
                font-weight: 500;
            }

            .settings-form select,
            .settings-form input[type="number"],
            .settings-form input[type="text"] {
                width: 80%;
                padding: 12px;
                border: 1px solid var(--border-color);
                border-radius: 8px;
                background: var(--bg-200);
                color: var(--text-primary);
                font-size: 14px;
                transition: all 0.3s ease;
            }

            .settings-form select:focus,
            .settings-form input[type="number"]:focus,
            .settings-form input[type="text"]:focus {
                border-color: #2196f3;
                box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1);
                outline: none;
            }

            .settings-form input[type="checkbox"] {
                margin-right: 8px;
            }

            .settings-form .checkbox-group {
                display: flex;
                align-items: center;
                margin-bottom: 12px;
            }

            .settings-form .checkbox-group label {
                margin-bottom: 0;
                margin-left: 4px;
                font-weight: normal;
            }

            .settings-form .form-hint {
                font-size: 12px;
                color: var(--text-secondary);
                margin-top: 4px;
            }

            .settings-form .error {
                border-color: #f44336;
            }

            .settings-form .error + .form-hint {
                color: #f44336;
            }

            @media (max-width: 480px) {
                .settings-form {
                    padding: 15px;
                }
            }
        `;

        // 移除旧样式
        const oldStyle = document.querySelector('style[data-settings-form]');
        if (oldStyle) {
            oldStyle.remove();
        }

        style.setAttribute('data-settings-form', 'true');
        document.head.appendChild(style);
    }

    // 添加新方法：加载设置
    loadSettings() {
        if (this.waterData.settings) {
            const settings = this.waterData.settings;

            // 设置基本信息
            document.getElementById('gender').value = settings.gender || 'male';
            document.getElementById('age').value = settings.age || '';
            document.getElementById('weight').value = settings.weight || '';
            document.getElementById('activity-level').value = settings.activityLevel || 'sedentary';

            // 设置提醒选项
            if (settings.reminder) {
                document.getElementById('reminder-enabled').checked = settings.reminder.enabled;
                document.getElementById('reminder-interval').value = settings.reminder.interval || 60;
                document.getElementById('notification-enabled').checked = settings.reminder.notification;
                document.getElementById('sound-enabled').checked = settings.reminder.sound;
            }
        }
    }

    startReminders() {
        if (this.reminderInterval) {
            clearInterval(this.reminderInterval);
        }

        if (this.waterData.settings.reminder.enabled) {
            const interval = this.waterData.settings.reminder.interval * 60 * 1000; // 转换为毫秒
            this.reminderInterval = setInterval(() => {
                this.checkAndRemind();
            }, interval);
        }
    }

    checkAndRemind() {
        const currentHour = new Date().getHours();
        const currentMinute = new Date().getMinutes();

        // 检查是否启用了提醒
        if (!this.waterData.settings.reminder.enabled) {
            return;
        }

        // 检查是否在提醒时间范围内（早6点到晚10点）
        if (currentHour >= 6 && currentHour <= 22) {
            const percentage = (this.waterData.currentAmount / this.waterData.dailyGoal) * 100;

            // 获取上次喝水时间
            const lastRecord = this.waterData.records[this.waterData.records.length - 1];
            const now = new Date().getTime();
            const timeSinceLastDrink = lastRecord
                ? (now - lastRecord.timestamp) / (60 * 1000) // 转换为分钟
                : Infinity;

            // 根据不同情况生成提醒消息
            let message = '';
            let priority = 'normal';

            if (percentage < 30 && currentHour >= 9) {
                message = '今天的饮水量还很少，记得补充水分哦！';
                priority = 'high';
            } else if (timeSinceLastDrink > 120) { // 超过2小时没喝水
                message = `已经${Math.floor(timeSinceLastDrink / 60)}小时${Math.floor(timeSinceLastDrink % 60)}分钟没有喝水了，起来活动一下，喝杯水吧！`;
                priority = 'high';
            } else if (percentage < 80 && currentHour >= 16) {
                message = `距离今日饮水目标还差${Math.round(this.waterData.dailyGoal - this.waterData.currentAmount)}ml，加油！`;
                priority = 'normal';
            }

            // 特殊时段提醒
            if (currentHour === 8 && currentMinute < 30) {
                message = '早上好！来一杯温水开启活力一天～';
                priority = 'normal';
            } else if (currentHour === 12 && currentMinute < 30) {
                message = '午餐时间到了，记得喝水哦！';
                priority = 'normal';
            } else if (currentHour === 15 && currentMinute < 30) {
                message = '下午茶时间，来杯水提提神吧！';
                priority = 'normal';
            } else if (currentHour === 21 && currentMinute < 30) {
                message = '睡前适量喝水，注意不要喝太多哦～';
                priority = 'normal';
            }

            if (message) {
                // 根据优先级决定是否播放提示音
                const shouldPlaySound = this.waterData.settings.reminder.sound && priority === 'high';
                this.showNotification(message, shouldPlaySound);
            }
        }
    }

    showNotification(message, type = 'info', playSound = false) {
        try {
            // 检查通知权限
            if (!("Notification" in window)) {
                console.warn("该浏览器不支持通知功能");
                this.showToast("该浏览器不支持通知功能", "warning");
                return;
            }

            // 请求通知权限
            if (Notification.permission === "default") {
                Notification.requestPermission().then(permission => {
                    if (permission === "granted") {
                        this.createNotification(message, type);
                    }
                });
                return;
            }

            if (Notification.permission === "granted") {
                this.createNotification(message, type);
            }

            // 播放提示音
            if (playSound && this.waterData.settings.reminder.sound) {
                this.playNotificationSound();
            }
        } catch (error) {
            console.error("创建通知时出错:", error);
            this.showToast("创建通知失败，请检查系统设置", "error");
        }
    }

    createNotification(message, type) {
        // 通知配置
        const icons = {
            'info': '/assets/icons/water-info.png',
            'success': '/assets/icons/water-success.png',
            'warning': '/assets/icons/water-warning.png',
            'reminder': '/assets/icons/water-reminder.png'
        };

        const options = {
            body: message,
            icon: icons[type] || icons.info,
            badge: icons.info,
            tag: 'water-reminder',
            renotify: true,
            requireInteraction: false,
            silent: !this.waterData.settings.reminder.sound,
            data: {
                type: type,
                timestamp: new Date().getTime()
            },
            actions: [
                {
                    action: 'add-water',
                    title: '记录饮水'
                },
                {
                    action: 'dismiss',
                    title: '稍后提醒'
                }
            ]
        };

        // 创建通知
        const notification = new Notification("喝水提醒", options);

        // 添加事件监听
        notification.onclick = (event) => {
            event.preventDefault();
            window.focus();
            if (event.action === 'add-water') {
                this.showAddWaterDialog();
            }
            notification.close();
        };

        notification.onclose = () => {
            // 可以在这里添加通知关闭后的逻辑
            console.log("通知已关闭");
        };

        notification.onerror = (error) => {
            console.error("通知显示失败:", error);
            this.showToast("通知显示失败，请检查系统设置", "error");
        };

        // 5秒后自动关闭
        setTimeout(() => {
            notification.close();
        }, 5000);
    }

    playNotificationSound() {
        try {
            const audio = new Audio('/assets/sounds/water-reminder.mp3');
            audio.volume = 0.5;
            audio.play().catch(error => {
                console.warn("播放提示音失败:", error);
            });
        } catch (error) {
            console.error("创建音频对象失败:", error);
        }
    }

    // 提示框功能
    showToast(message, type = 'info') {
        const container = document.getElementById('toast-container');

        // 如果容器不存在，创建一个
        if (!container) {
            const newContainer = document.createElement('div');
            newContainer.id = 'toast-container';
            document.body.appendChild(newContainer);
        }

        // 检查是否已存在相同内容的提示
        const existingToasts = document.getElementsByClassName('toast');
        for (let toast of existingToasts) {
            if (toast.textContent === message) {
                return; // 如果存在相同内容的提示，则不创建新的
            }
        }

        const toast = document.createElement('div');
        toast.className = `toast ${type}`;

        // 根据类型选择图标
        let icon = '';
        switch (type) {
            case 'success':
                icon = '<i class="fas fa-check-circle"></i>';
                break;
            case 'error':
                icon = '<i class="fas fa-times-circle"></i>';
                break;
            default:
                icon = '<i class="fas fa-info-circle"></i>';
        }

        toast.innerHTML = `${icon}${message}`;
        document.getElementById('toast-container').appendChild(toast);

        // 5秒后移除
        setTimeout(() => {
            if (document.getElementById('toast-container').contains(toast)) {
                toast.style.animation = 'fadeOut 0.3s ease forwards';
                toast.addEventListener('animationend', (e) => {
                    if (e.animationName === 'fadeOut' &&
                        document.getElementById('toast-container') &&
                        document.getElementById('toast-container').contains(toast)) {
                        document.getElementById('toast-container').removeChild(toast);
                    }
                });
            }
        }, 3000);
    }

    deleteRecord(timestamp) {
        const recordIndex = this.waterData.records.findIndex(r => r.timestamp === timestamp);
        if (recordIndex !== -1) {
            const record = this.waterData.records[recordIndex];
            this.waterData.currentAmount -= record.amount;
            this.waterData.records.splice(recordIndex, 1);
            this.saveData();
            this.updateUI();
            this.showToast(`已删除 ${record.amount}ml ${record.drinkName} 的记录`, 'warning');
        }
    }
}

// 当DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.waterTracker = new WaterTracker();
}); 

// 导出模块
module.exports = {
    WaterTracker
};